package io.renren.config.security.filter;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.R;
import io.renren.modules.sys.service.SysCaptchaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 用来校验登录时候的验证码
 * @author: TanJingyu
 * @create: 2021-11-06 13:11
 **/
@Component
@RequiredArgsConstructor
public class CaptchaFilter extends GenericFilterBean {
    private final SysCaptchaService captchaService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if ("/login".equals(req.getRequestURI()) && "post".equals(req.getMethod())) {
            String captcha = req.getParameter("captcha");
            String uuid = req.getParameter("uuid");

            boolean validate = captchaService.validate(uuid, captcha);

            if (validate) {
                filterChain.doFilter(req, res);
            }else {
                res.setContentType("application/json;charset=utf-8");
                PrintWriter writer = res.getWriter();

                writer.write(JSON.toJSONString(R.error("验证码不正确")));
                writer.flush();
                writer.close();
            }
        }else {
            filterChain.doFilter(req, res);
        }
    }
}
